package de.hsowl.tod4a.client.http;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.Socket;

import de.hsowl.tod4a.global.http.HttpRequest;
import de.hsowl.tod4a.global.http.HttpResponse;
import de.hsowl.tod4a.global.model.ClientProperty;

public class HttpClient extends Socket {

	private boolean close = true;
	private InetSocketAddress remoteAddr;
	private InetSocketAddress proxyAddr;
	private int timeout;
	private HttpRequest req = new HttpRequest();

	public HttpClient(String url, int port, int timeout, String username, String password, ClientProperty props) {
		this.remoteAddr = new InetSocketAddress(url, port);
		this.timeout = timeout;
		req.USER += username;
		req.PASSWORD += password;

		if (props != null && props.getProxyHost() != null && props.getProxyPort() > 0) {
			this.remoteAddr = new InetSocketAddress(props.getProxyHost(), props.getProxyPort());
		}
	}

	/**
	 * Sends a message within a http header
	 * 
	 * @param msg
	 * @return
	 * @throws IOException
	 */
	public HttpResponse send(String msg) throws IOException {
		if (remoteAddr != null) {

			if (close == true) {
				connect();
			}

			super.getOutputStream().write(req.getHeader(remoteAddr.getHostName(), msg));
			HttpResponse resp = HttpResponse.getResponse(super.getInputStream());

			return resp;
		} else {
			throw new NullPointerException("address == null");
		}
	}

	/**
	 * Connects to a remote server
	 * 
	 * @param addr
	 * @param timeout
	 * @throws IOException
	 */
	public void connect() throws IOException {
		if (proxyAddr != null) {
			super.connect(proxyAddr, timeout);
		} else {
			super.connect(remoteAddr, timeout);
		}
		close = false;
	}

	/**
	 * Closes the connection
	 */
	public void close() {
		try {
			super.close();
			close = true;
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
}
